<template>
  <div class="department-view">
    <!-- 页面标题栏 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">
          <i class="el-icon-office-building"></i>
          系管理
        </h1>
        <p class="page-description">管理学校的院系信息</p>
      </div>
      <div class="header-right">
        <el-button type="primary" icon="el-icon-plus" @click="showAddDialog">
          新增系
        </el-button>
      </div>
    </div>
      
      <!-- 搜索和筛选区域 -->
      <el-card class="search-card" shadow="never">
        <div slot="header" class="card-header">
          <span><i class="el-icon-search"></i> 搜索筛选</span>
        </div>
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="系名称">
            <el-input 
              v-model="searchForm.name" 
              placeholder="请输入系名称" 
              clearable
              style="width: 240px;"
              @keyup.enter.native="handleSearch">
              <i slot="prefix" class="el-input__icon el-icon-search"></i>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleSearch">
              搜索
            </el-button>
            <el-button icon="el-icon-refresh" @click="resetSearch">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 数据表格区域 -->
      <el-card class="table-card" shadow="never">
        <div slot="header" class="card-header">
          <span><i class="el-icon-menu"></i> 系列表</span>
          <span class="table-count">共 {{ total }} 条记录</span>
        </div>
        
        <el-table 
          :data="tableData" 
          style="width: 100%" 
          v-loading="loading"
          stripe
          border
          empty-text="暂无数据">
          <el-table-column prop="id" label="系ID" width="100" align="center">
            <template slot-scope="scope">
              <el-tag size="mini" type="info">{{ scope.row.id }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="系名称" min-width="200">
            <template slot-scope="scope">
              <div class="name-cell">
                <i class="el-icon-office-building name-icon"></i>
                <span class="name-text">{{ scope.row.name }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="majorCount" label="专业数" width="120" align="center">
            <template slot-scope="scope">
              <el-tag size="small" type="success">
                {{ scope.row.majorCount || 0 }} 个专业
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="teacherCount" label="教师数" width="120" align="center">
            <template slot-scope="scope">
              <el-tag size="small" type="warning">
                {{ scope.row.teacherCount || 0 }} 名教师
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160" align="center" fixed="right">
            <template slot-scope="scope">
              <div class="action-buttons">
                <el-button 
                  size="mini" 
                  type="primary" 
                  icon="el-icon-edit"
                  @click="handleEdit(scope.row)"
                  class="action-btn edit-btn">
                  编辑
                </el-button>
                <el-button 
                  size="mini" 
                  type="danger" 
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  class="action-btn delete-btn">
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页组件 -->
        <div class="pagination-container">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            background>
          </el-pagination>
        </div>
      </el-card>

      <!-- 新增/编辑对话框 -->
      <el-dialog 
        :title="dialogTitle" 
        :visible.sync="dialogVisible" 
        width="500px"
        :close-on-click-modal="false"
        @close="handleDialogClose">
        <el-form 
          :model="form" 
          :rules="rules" 
          ref="form" 
          label-width="100px"
          label-position="right">
          <el-form-item label="系名称" prop="name">
            <el-input 
              v-model="form.name" 
              placeholder="请输入系名称"
              maxlength="50"
              show-word-limit
              clearable>
              <i slot="prefix" class="el-input__icon el-icon-office-building"></i>
            </el-input>
          </el-form-item>
        </el-form>
        
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false" icon="el-icon-close">
            取消
          </el-button>
          <el-button 
            type="primary" 
            @click="handleSubmit" 
            :loading="submitLoading"
            icon="el-icon-check">
            {{ submitLoading ? '提交中...' : '确定' }}
          </el-button>
        </div>
      </el-dialog>
    </div>
</template>

<script>
import { getDepartmentPage, getDepartmentPageCount, saveDepartment, deleteDepartment, getDepartmentById } from '@/api'

export default {
  name: 'DepartmentView',
  data() {
    return {
      searchForm: {
        name: ''
      },
      tableData: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: '新增系',
      submitLoading: false,
      form: {
        id: -1,
        name: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入系名称', trigger: 'blur' },
          { min: 2, max: 50, message: '系名称长度在 2 到 50 个字符', trigger: 'blur' },
          { pattern: /^[\u4e00-\u9fa5a-zA-Z0-9\s]+$/, message: '系名称只能包含中文、英文、数字和空格', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    async loadData() {
      this.loading = true
      try {
        // 获取总页数
        const countRes = await getDepartmentPageCount(this.searchForm)
        if (countRes.code === 0) {
          this.total = countRes.data * this.pageSize
        }

        // 获取当前页数据
        const res = await getDepartmentPage(this.currentPage, this.searchForm)
        if (res.code === 0) {
          this.tableData = res.data || []
        }
      } catch (error) {
        this.$message.error('加载数据失败')
        console.error('加载系列表数据失败:', error)
      } finally {
        this.loading = false
      }
    },
    
    handleSearch() {
      this.currentPage = 1
      this.loadData()
    },
    
    resetSearch() {
      this.searchForm = { name: '' }
      this.handleSearch()
    },
    
    showAddDialog() {
      this.dialogTitle = '新增系'
      this.form = { id: -1, name: '' }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.clearValidate()
      })
    },
    
    async handleEdit(row) {
      try {
        this.loading = true
        const res = await getDepartmentById(row.id)
        if (res.code === 0) {
          this.dialogTitle = '编辑系'
          this.form = { ...res.data }
          this.dialogVisible = true
          this.$nextTick(() => {
            this.$refs.form && this.$refs.form.clearValidate()
          })
        } else {
          this.$message.error(res.message || '获取系信息失败')
        }
      } catch (error) {
        this.$message.error('获取系信息失败')
        console.error('获取系信息失败:', error)
      } finally {
        this.loading = false
      }
    },
    
    handleDelete(row) {
      this.$confirm(`确定要删除系"${row.name}"吗？`, '确认删除', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(async () => {
        try {
          const res = await deleteDepartment(row.id)
          if (res.code === 0) {
            this.$message.success('删除成功')
            // 如果当前页没有数据了，回到上一页
            if (this.tableData.length === 1 && this.currentPage > 1) {
              this.currentPage--
            }
            this.loadData()
          } else {
            this.$message.error(res.message || '删除失败')
          }
        } catch (error) {
          this.$message.error('删除失败')
          console.error('删除系失败:', error)
        }
      }).catch(() => {
        // 用户取消删除
      })
    },
    
    async handleSubmit() {
      try {
        await this.$refs.form.validate()
        this.submitLoading = true
        
        const res = await saveDepartment(this.form)
        if (res.code === 0) {
          this.$message.success(this.form.id === -1 ? '新增成功' : '编辑成功')
          this.dialogVisible = false
            // 如果是新增，跳转到第一页
          if (this.form.id === -1) {
            this.currentPage = 1
          }
          this.loadData()
        } else {
          this.$message.error(res.message || (this.form.id === -1 ? '新增失败' : '编辑失败'))
        }
      } catch (error) {
        if (error === false) {
          // 表单验证失败
          return
        }
        this.$message.error(this.form.id === -1 ? '新增失败' : '编辑失败')
        console.error('保存系信息失败:', error)
      } finally {
        this.submitLoading = false
      }
    },
    
    handleDialogClose() {
      this.$refs.form && this.$refs.form.resetFields()
      this.submitLoading = false
    },
    
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.loadData()
    },
    
    handleCurrentChange(val) {
      this.currentPage = val
      this.loadData()
    }
  }
}
</script>

<style scoped>
.department-view {
  padding: 24px;
  min-height: calc(100vh - 120px);
  background: #f5f6fa;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #e8e9ea;
}

.header-left { flex: 1; }
.page-title { margin: 0 0 8px 0; font-size: 28px; font-weight: 700; color: #1a1a1a; display: flex; align-items: center; }
.page-title i { margin-right: 12px; color: #409eff; font-size: 32px; }
.page-description { margin: 0; color: #6c757d; font-size: 15px; font-weight: 400; }
.header-right { display: flex; align-items: center; }

/* 卡片头部 */
.card-header { display: flex; justify-content: space-between; align-items: center; font-weight: 600; color: #262626; font-size: 16px; }
.table-count { font-size: 14px; color: #909399; }

.search-card { margin-bottom: 16px; }
.table-card { margin-top: 16px; }
.pagination-container { margin-top: 16px; text-align: right; }

.name-cell { display: flex; align-items: center; }
.name-icon { margin-right: 8px; color: #409eff; }

.action-buttons { display: flex; gap: 8px; justify-content: center; align-items: center; }

:deep(.action-btn) { width: 60px !important; height: 28px !important; padding: 0 !important; border-radius: 4px !important; font-size: 12px !important; display: flex !important; align-items: center !important; justify-content: center !important; min-width: 60px !important; }
:deep(.edit-btn) { background-color: #409eff !important; border-color: #409eff !important; color: white !important; }
:deep(.edit-btn:hover) { background-color: #66b1ff !important; border-color: #66b1ff !important; }
:deep(.delete-btn) { background-color: #f56c6c !important; border-color: #f56c6c !important; color: white !important; }
:deep(.delete-btn:hover) { background-color: #f78989 !important; border-color: #f78989 !important; }
</style>
